use std::fs::File;
use std::io::Read;
use std::path::Path;
use axum::response::{IntoResponse, Response};
use axum::extract::{Multipart, Path as AxumPath, Query, State};
use http::{header, StatusCode};
use serde::Deserialize;
use crate::config::address;
use crate::models::AppState::AppState;
#[derive(Deserialize, Debug)]
pub struct DownloadFileRequest{
    id: u64,
    name: String,
}
pub async fn download_file(State(state):State<AppState>,Query(file):Query<DownloadFileRequest>) -> impl IntoResponse {
    // 1. 使用 ID 查询对应的 MD5
    let id = file.id;
    let name = file.name;
    println!("{}{}", id,name);
    let mut file_databases = state.file_database.clone();
    let mut file = file_databases.lock().await;
    let md5 = file.id_md5.get(&id).unwrap().clone();
    println!("{:?}", md5);
    let file_name = format!("{}_{}",name.clone(),md5.clone());
    let file_path = format!("{}/{}_{}",address,name,md5.clone());
    println!("{:?}", file_path);
    let path = Path::new(&file_path);
    // 检查文件是否存在
    if !path.exists() {
        return (StatusCode::NOT_FOUND, "File not found".to_string()).into_response();
    }
    let mut file = match File::open(path) {
        Ok(f) => f,
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    };
    let mut buffer = Vec::new();
    if let Err(e) = file.read_to_end(&mut buffer) {
        return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
    }
    let mut response = Response::new(buffer.into());
    response.headers_mut().insert(
        header::CONTENT_TYPE,
        header::HeaderValue::from_static("application/octet-stream"),
    );
    response.headers_mut().insert(
        header::CONTENT_DISPOSITION,
        header::HeaderValue::from_str(&format!("attachment; filename=\"{}\"", file_name)).unwrap(),
    );
    response
}